import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { useNavigate } from "react-router-dom";
import emitter from "../bus.js";
import AIIcon from "../../../assets/images/AI.png";
import aiBg1 from "../../../assets/images/aibg1.png";
import aiBg2 from "../../../assets/images/aibg2.png";
import aiBg3 from "../../../assets/images/aibg3.png";
import aiBg4 from "../../../assets/images/aibg4.png";
import aiBg5 from "../../../assets/images/aibg5.png";

// Import components
import CalendarPlan from '../../agents/calendarPlan.jsx';
import MailHanding from '../../agents/mailHanding';
import BossCalledMe from '../../agents/bossCalledMe';
import MailList from '../../agents/mailList';
import WriteEmail from '../../agents/writeEmail';
import ProjectPlan from '../../agents/projectPlan';
import SquareEnd from '../../agents/squareend';
import { fetchSharePointListData } from '../../../config/api/api.js'; 

const Square = (props) => {
  console.log('Square props:', props);
  const [cardList, setCardList] = useState([])
  const navigate = useNavigate();
  const getAgentList = async () => {
    const items = await fetchSharePointListData('c793107a-2558-4107-a18f-aed980c310cc');
    const tablelist = items.map(item => {
      return {
        id: item.Id,
        title: item.Title,
        content: item.content,
        iconUrl: item.attachmentUrls.length > 0 ? item.attachmentUrls[0] : '',
        dept: item.labels,
        isChat: item.isChat ,
        bot_id: item.bot_id,
      }
    })
    console.log('tablelist',tablelist)
    setCardList(tablelist)
  }

  useEffect(() => {
    getAgentList();
  }, []);

  const [selectedComponent, setSelectedComponent] = useState(null);

  useEffect(() => {
    // Listen for reset event
    const handleReset = () => {
      setSelectedComponent(null);
    };

    emitter.on('resetSquare', handleReset);

    return () => {
      emitter.off('resetSquare', handleReset);
    };
  }, []);

  const componentMap = {
    "1": CalendarPlan,
    "2": MailHanding,
    "3": BossCalledMe,
    "4": MailList,
    "5": WriteEmail,
    "6": ProjectPlan,
    "8": SquareEnd
  };

  const handCard = (data) => {
    // 确保dataObj有bot_id字段
    const dataObj = {
      bot_id: data.bot_id,
      index: data.isChat === "true" ? 1 : 2,
      id: data.id,
      isChat: data.isChat
    };
    setSelectedComponent({ id: data.id, dataObj });
    emitter.emit('message', dataObj);
    props.handTabChange(dataObj);
  };

  const renderSelectedComponent = () => {
    if (!selectedComponent) return null;
    const Component = componentMap[selectedComponent.id];
    return Component ? (
      <div className="selected-component-container">
        <Component 
          dataObj={selectedComponent.dataObj} 
          context={props.context} // 传递 SharePoint context
        />
      </div>
    ) : null;
  };

  return (
    <div className="square-container">
    {selectedComponent ? (
      renderSelectedComponent()
    ) : (
      <div> 
      <div className="square-header">
      <span className="square-title">AI智能体</span>
    </div>
    <div className="home-card">
      {cardList.map((card) => (
        <div
          key={card.id}
          className="card-item"
          onClick={() => handCard(card)}
        >
          <div className="card-title-container">
            <div className="card-title">
              <div className="notice-icon" ><img src={card.iconUrl}></img></div>
              {card.title}</div>
          </div>
          <p className="card-desc">{card.content}</p>
        </div>
      ))}
    </div>
      </div>
    )}
      <style jsx="true">{`
        .selected-component-container {
          margin-left: 40px;
        }
        .square-container {
          width: calc(100vw - 270px);
          min-width: 1230px;
          height: 100%;
          display: flex;
          flex-direction: column;
          position: relative;
          margin: 2.5vh 24px 2.5vh 0;
          margin-left: 140px;
          border-radius: 14px;
        }
        .main-container{
          width:100vw !important;
          height:100% !important;
        }
        .square-header {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 40px;
          margin: 20px;
          margin-top:100px;
        }
        
        .square-header img {
          width:auto;
          margin-right: 10px;
        }
        
        .square-title {
          font-size: 20px;
          font-weight: 700;
        }
        
        .el-card {
          background-color: #fff;
          width: 405px;
          height: 300px;
          margin: 5px;
          cursor: pointer;
          display: flex;
          justify-content: center;
          align-items: stretch;
          border-radius: 8px;
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }
        
        .card-content {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          width: 100%;
          padding: 16px;
          box-sizing: border-box;
        }
        
        .card-title {
          font-size: 15px;
          font-weight: 700;
          margin-top: 20px;
          margin-left: 10px;
          margin-bottom: 10px;
        }
        
        .card-desc {
          flex-grow: 1;
          font-size: 12px;
          margin-left: 10px;
          color: #999999;
          width: 200px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }
        
        .card-btn {
          display: flex;
          justify-content: center;
          align-items: center;
          position: relative;
          top: -26px;
          font-size: 12px;
        }
        
        .card-btn button {
          padding: 15px 30px;
        }
        
        .right-icon {
          margin-left: 5px;
          font-size: 14px;
        }
        
        .card-container {
          display: flex;
          flex-direction: row;
          min-width: 1400px;
          flex-wrap: wrap;
          margin: 0 20px;
          padding-bottom:120px;
          overflow-y: auto;
          gap: 16px;
        }

        .home-card{
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 20px;
          padding: 20px;
          margin:20px auto;
        }
        .card-item{
          border-radius: 16px;
          background-color: white;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          padding: 10px 20px;
          height:117px;
          cursor: pointer;
        }
        .notice-icon{
          position: relative;
          top: 2px;
          margin-right: 10px;
        }
        .card-title-container{
          display: flex;
          align-items: center;
        }
        .card-title{
          display: flex;
          flex-direction: row;
          font-weight:500;
        }
        .j_b_8474018e{
          width: 100vw !important;
        }
          
                  .c_b_4ade22aa{
            display: flex !important;
    flex-direction: row !important;
            }
      `}</style>
    </div>
  );
};

Square.defaultProps = {
  handTabChange: () => { }
};

export default Square;